package com.qiangesoft.ocr.utils;

import com.aliyun.dytnsapi20200217.models.*;
import com.aliyun.dytnsapi20200217.models.CertNoTwoElementVerificationRequest;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;

/**
 * 阿里云ocr识别
 *
 * @author qiangesoft
 * @date 2025-03-27
 */
public class AliyunOcr {

    private static final String ACCESS_KEY_ID = "xxx";

    private static final String ACCESS_KEY_SECRET = "xxx";

    /**
     * 调用OCR识别身份证信息
     * https://help.aliyun.com/zh/ocr/developer-reference/api-ocr-api-2021-07-07-recognizeidcard
     *
     * @param imgUrl
     * @return
     * @throws Exception
     */
    public RecognizeIdcardResponse recognizeIDCard(String imgUrl) throws Exception {
        Config config = new Config()
                .setAccessKeyId(System.getenv(ACCESS_KEY_ID))
                .setAccessKeySecret(System.getenv(ACCESS_KEY_SECRET));
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        Client client = new Client(config);

        RecognizeIdcardRequest recognizeIdcardRequest = new RecognizeIdcardRequest();
        recognizeIdcardRequest.setUrl(imgUrl);
        RuntimeOptions runtime = new RuntimeOptions();
        return client.recognizeIdcardWithOptions(recognizeIdcardRequest, runtime);
    }

    /**
     * 调用身份信息核验API
     * https://api.aliyun.com/document/Dytnsapi/2020-02-17/CertNoTwoElementVerification
     *
     * authCode从这里获取：https://dytns.console.aliyun.com/analysis/square?spm=api-workbench.api_explorer.0.0.14c610915R4RUL
     *
     * @param name
     * @param idCard
     * @return
     * @throws TencentCloudSDKException
     */
    public CertNoTwoElementVerificationResponse idCardVerification(String name, String idCard) throws Exception {
        Config config = new Config()
                .setAccessKeyId(System.getenv(ACCESS_KEY_ID))
                .setAccessKeySecret(System.getenv(ACCESS_KEY_SECRET));
        config.endpoint = "dytnsapi.aliyuncs.com";
        com.aliyun.dytnsapi20200217.Client client = new com.aliyun.dytnsapi20200217.Client(config);

        CertNoTwoElementVerificationRequest certNoTwoElementVerificationRequest = new CertNoTwoElementVerificationRequest()
                .setAuthCode("your_value")
                .setCertName(name)
                .setCertNo(idCard);
        return client.certNoTwoElementVerificationWithOptions(certNoTwoElementVerificationRequest, new RuntimeOptions());
    }

}